//index.js
const wechat = require('../../utils/wechat_commen.js')
//获取应用实例
const app = getApp()
// 引入SDK核心类
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
var locationInfo;
var destinationCity = "目的地";
var hotIndex = 0
Page({
  data: {
    userInfo: {},
    isUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    destinationCity: destinationCity,
    color: "rgb(150, 150, 150)",
    checkInOutDate: "入住-离开时间",
    colorCheck: "rgb(150, 150, 150)",
    bgColor: "rgb(204,204,204)",
    nameTitle: '朋友，很高兴遇见你',
    iconName: '',
    isPhoneLogin: false,
    cityName: '',
    areaCode: '',
    latitude: '',
    longitude: '',
    checkDate: '',
    startTime: '',
    endTime: ''
  },
  wechat: wechat,
  onLoad: function() {

    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'NFYBZ-MRO36-YNKSR-MATSH-FZGFZ-4LFLO'
    });
    this.getUserInfoEvent()
    this.getLocationInfo()
    this.setLocationPermission();
    this.setButton();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    hotIndex = this.data.hotIndex
    console.log(hotIndex)
    var userIcon = wx.getStorageSync('userIcon')
    var title = wx.getStorageSync('userNickname')
    var that = this;
    if (title != null && title != "") {
      that.setData({
        iconName: userIcon,
        nameTitle: title
      })
    } else {
      that.setData({
        iconName: userIcon,
        nameTitle: '朋友，很高兴遇见你',
      })
    }
  },
  destination_click: function(e) {
    console.log(hotIndex)
    wx.navigateTo({
      url: '../destination/destination?location={{destinationCity}}&hotIndex=' + hotIndex,
    })
  },
  calendar_click: function(e) {
    var that = this
    wx.navigateTo({
      url: '../calendar/calendar?startTime=' + that.data.startTime + '&endTime=' + that.data.endTime + '&isRoomList=' + false,
    })
  },

  setButton() {
    if (this.data.destinationCity == '目的地') {
      this.setData({
        bgColor: "rgb(204,204,204)"
      })
    } else {
      this.setData({
        bgColor: "rgb(52,229,234)"
      })
    }
  },

  getUserInfo: function(e) {
    console.log(e)
    var that = this;
    app.globalData.userInfo = e.detail.userInfo
    if (app.globalData.userInfo) {
      // 存储用户微信头像和用户名
      wx.setStorageSync('userIcon', e.detail.userInfo.avatarUrl)
      wx.setStorageSync('userNickname', e.detail.userInfo.nickName)
      wx.setStorageSync('latelyUserIcon', e.detail.userInfo.avatarUrl)
      wx.setStorageSync('latelyUserNickname', e.detail.userInfo.nickName)

      this.setData({
        userInfo: e.detail.userInfo,
        nameTitle: e.detail.userInfo.nickName,
        iconName: e.detail.userInfo.avatarUrl,
        isUserInfo: true
      })
    }
    this.setLocationPermission();
  },

  setLocationPermission() {
    var that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              that.getLocationPermission()
            },
            fail() {
              that.destinationCity = "北京"
              that.setData({
                destinationCity: "北京",
                color: "rgb(51,51,51)",
                bgColor: "rgb(52,229,234)"
              })
              wx.showModal({
                title: '是否进行微信定位授权',
                content: '若不授权微信定位，则无法自动获取当前位置',
                success: function(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: function(res) {
                        if (res.authSetting["scope.userLocation"] || res.authSetting["scope.userInfo"]) {
                          //这里是授权成功之后 填写你重新获取数据的js
                          //参考:
                          that.getLocationPermission();
                          that.data.canIUse = false;
                          that.getUserInfoEvent();
                        }
                      }
                    })
                  }
                }
              })
            }
          })
        }
      }
    })

  },

  getLocationPermission() {
    var that = this;
    //用户同意授权
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.locationInfo = res
        that.getLocationInfo()
      }
    })
  },

  //获取微信用户头像信息的结果处理
  getUserInfoEvent() {
    var that = this;
    var userinfo = app.globalData.userInfo; //是否有缓存微信信息
    if (userinfo) { //有缓存信息
      console.log("userinfo", userinfo);
      that.setData({
        userInfo: userinfo,
        nameTitle: userinfo.nickName,
        iconName: userinfo.avatarUrl,
        isUserInfo: true
      })
    } else if (that.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        that.setData({
          userInfo: res.userInfo,
          nameTitle: res.userInfo.nickName,
          iconName: res.userInfo.avatarUrl,
          isUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          that.setData({
            userInfo: res.userInfo,
            nameTitle: res.userInfo.nickName,
            iconName: res.userInfo.avatarUrl,
            isUserInfo: true
          })
        }
      })
    }

  },

  //获取地理位置回调结果处理
  getLocationInfo() {
    locationInfo = app.globalData.locationInfo;
    var that = this;
    if (!locationInfo) { //1、定位授权
      app.locationInfoReadyCallback = res => {
        that.setData({
          locationInfo: res
        })
        console.log(res);
        wechat.setStorageSync("latitude", res.latitude);
        wechat.setStorageSync("lontitude", res.longitude);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })

        if (res) {
          // 2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function(addressRes) {
              var address = addressRes.result.formatted_addresses.recommend;
              wechat.setStorageSync("location_address", address);
              var city = addressRes.result.address_component.city
              if (city.indexOf('市')) {
                city = city.split('市')[0]
              } else {
                city = city
              }
              that.destinationCity = address
              that.setData({
                destinationCity: address,
                color: "rgb(51,51,51)",
                bgColor: "rgb(52,229,234)",
                cityName: city
              })
            }
          })
        }
      }
    } else {
      //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
      wechat.setStorageSync("latitude", locationInfo.latitude);
      wechat.setStorageSync("lontitude", locationInfo.longitude);
      that.setData({
        latitude: locationInfo.latitude,
        longitude: locationInfo.longitude
      })
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: locationInfo.latitude,
          longitude: locationInfo.longitude
        },
        success: function(addressRes) {
          console.log('Adddd :  ' + addressRes)
          var address = addressRes.result.formatted_addresses.recommend;
          var city = addressRes.result.address_component.city
          if (city.indexOf('市')) {
            city = city.split('市')[0]
          } else {
            city = city
          }
          wechat.setStorageSync("location_address", address);
          that.destinationCity = address
          that.setData({
            destinationCity: address,
            color: "rgb(51,51,51)",
            bgColor: "rgb(52,229,234)",
            cityName: city
          })
        }
      })
    }
  },
  searchCity: function(e) {
    var that = this;
    if (this.data.destinationCity == "北京") {
      that.setData({
        areaCode: '010'
      })
    }
    var dd = '../roomlist/roomlist?destination=' + this.data.destinationCity + '&startTime=' + this.data.startTime + '&endTime=' + this.data.endTime + '&latitude=' + that.data.latitude + '&longitude=' + that.data.longitude + '&areaCode=' + that.data.areaCode +
      '&cityName=' + that.data.cityName
    console.log(dd)
    if (this.data.destinationCity != "目的地") {
      wx.navigateTo({
        url: '../roomlist/roomlist?destination=' + this.data.destinationCity + '&startTime=' + this.data.startTime + '&endTime=' + this.data.endTime + '&latitude=' + that.data.latitude + '&longitude=' + that.data.longitude + '&areaCode=' + that.data.areaCode +
          '&cityName=' + that.data.cityName,
      })
    } else {
      wx.showToast({
        title: '请选择目的地',
        duration: 2000
      })
    }
  }

})